package com.lishu.carsafe.activity;

import android.Manifest;
import android.annotation.TargetApi;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.lishu.carsafe.R;
import com.lishu.carsafe.http.HttpBase;
import com.lishu.carsafe.http.HttpLoader;
import com.lishu.carsafe.listener.UploadFileListener;
import com.lishu.carsafe.model.BaseModel;
import com.lishu.carsafe.model.FaultToAddModel;
import com.lishu.carsafe.model.UploadFileModel;
import com.lishu.carsafe.model.entity.Level;
import com.lishu.carsafe.model.entity.Type;
import com.lishu.carsafe.model.entity.VehicleId;
import com.lishu.carsafe.utils.ImageUtil;
import com.lishu.carsafe.utils.ListUtil;
import com.lishu.carsafe.utils.LogUtil;
import com.lishu.carsafe.utils.StringUtil;
import com.lishu.carsafe.utils.TimeUtil;
import com.lishu.carsafe.utils.ToastUtil;
import com.lishu.carsafe.widget.ChooseDialog;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class FaultEditBaseActivity extends BaseActivity{
    private final int GET_PERMISSION_REQUEST = 200; //权限申请自定义码
    protected EditText fault_title, fault_car, fault_location, fault_level, fault_type, fault_detail;
    protected ImageView upload_1, upload_2, video_icon;

    protected String mediaType = "0";//0照片1视频
    protected String localMediaUrl;
    private String uploadedMediaUrl;
    private File cameraFile;

    private List<VehicleId> mVehicles = new ArrayList<>();
    private List<Level> mLevels = new ArrayList<>();
    private List<Type> mTypes = new ArrayList<>();
    protected Type selectedCar = new Type();
    protected Type selectedLevel = new Type();
    protected Type selectedType = new Type();

    protected void initView() {
        fault_title = findViewById(R.id.fault_title);
        fault_car = findViewById(R.id.fault_car);
        fault_location = findViewById(R.id.fault_location);
        fault_level = findViewById(R.id.fault_level);
        fault_type = findViewById(R.id.fault_type);
        fault_detail = findViewById(R.id.fault_detail);
        upload_1 = findViewById(R.id.upload_1);
        upload_2 = findViewById(R.id.upload_2);
        video_icon = findViewById(R.id.video_icon);
    }

    protected void testOptions() {
        for(int i = 0; i < 5; i++){
            VehicleId type = new VehicleId();
            type.setId("" + i);
            type.setName("选项" + i);
            mVehicles.add(type);
        }
        for(int i = 0; i < 1; i++){
            Level type = new Level();
            type.setId("" + i);
            type.setParamName("选项" + i);
            mLevels.add(type);
        }
    }

    protected void getFaultOptions() {
        HttpLoader.getFaultToAdd( new HttpBase.IResponseListener() {
            @Override
            public void onResponse(BaseModel model) {
                if (model == null) {
                    hide();
                    ToastUtil.showShort(R.string.please_check_network);
                    return;
                }
                if (!model.success()) {
                    hide();
                    ToastUtil.showShort(getString(R.string.get_data_fail) + model.getMsg());
                    return;
                }
                FaultToAddModel.FaultToAdd faultOptions = ((FaultToAddModel) model).getData();
                List<VehicleId> vehicles = faultOptions.getVehicles();
                List<Level> levels = faultOptions.getLevels();
                List<Type> types = faultOptions.getTypes();
                if(!ListUtil.isEmpty(vehicles)){
                    mVehicles.addAll(vehicles);
                }
                if(!ListUtil.isEmpty(levels)){
                    mLevels.addAll(levels);
                }
                if(!ListUtil.isEmpty(types)){
                    mTypes.addAll(types);
                }
            }
        });
    }

    protected void chooseNumberDialog(int commType){
        final ChooseDialog chooseDialog = new ChooseDialog(this);
        List<Type> optionList = new ArrayList<>();

        switch (commType){
            case 1:
                if(ListUtil.isEmpty(mVehicles)){
                    ToastUtil.showShort("无可选车辆");
                }
                chooseDialog.setDialogTitle("请选择故障车辆");

                optionList.clear();
                for(int i = 0; i < mVehicles.size(); i++){
                    Type type = new Type();
                    type.setId(mVehicles.get(i).getId());
                    type.setParamName(mVehicles.get(i).getName());
                    optionList.add(type);
                }
                chooseDialog.setDialogData(optionList);
                chooseDialog.setItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        chooseDialog.dismissDialog();
                        selectedCar = (Type) parent.getItemAtPosition(position);
                        fault_car.setText(selectedCar.getParamName());
                    }
                });
                break;
            case 2:
                if(ListUtil.isEmpty(mLevels)){
                    ToastUtil.showShort("无可选故障等级");
                }
                chooseDialog.setDialogTitle("请选择故障等级");

                optionList.clear();
                for(int i = 0; i < mLevels.size(); i++){
                    Type type = new Type();
                    type.setId(mLevels.get(i).getId());
                    type.setParamName(mLevels.get(i).getParamName());
                    optionList.add(type);
                }
                chooseDialog.setDialogData(optionList);
                chooseDialog.setItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        chooseDialog.dismissDialog();
                        selectedLevel = (Type) parent.getItemAtPosition(position);
                        fault_level.setText(selectedLevel.getParamName());
                    }
                });
                break;
            case 3:
                if(ListUtil.isEmpty(mTypes)){
                    ToastUtil.showShort("无可选故障类型");
                }
                chooseDialog.setDialogTitle("请选择故障类型");

                chooseDialog.setDialogData(mTypes);
                chooseDialog.setItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        chooseDialog.dismissDialog();
                        selectedType = (Type) parent.getItemAtPosition(position);
                        fault_type.setText(selectedType.getParamName());
                    }
                });
                break;
        }
    }

    protected boolean check(String title, String car, String location, String level,
                            String type, String detail) {
        if (StringUtil.isEmpty(title)) {
            ToastUtil.showShort("请填写标题");
            return false;
        }else if (StringUtil.isEmpty(car)) {
            ToastUtil.showShort("请选择车辆");
            return false;
        }else if (StringUtil.isEmpty(location)) {
            ToastUtil.showShort("请填写故障发生地点");
            return false;
        }else if (StringUtil.isEmpty(level)) {
            ToastUtil.showShort("请选择故障等级");
            return false;
        }else if (StringUtil.isEmpty(type)) {
            ToastUtil.showShort("请选择故障类型");
            return false;
        }else if (StringUtil.isEmpty(detail)) {
            ToastUtil.showShort("请简短描述故障信息（不超过50字）");
            return false;
        }

        return true;
    }

    /**
     * 获取权限
     */
    protected void getPermissions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager
                    .PERMISSION_GRANTED &&
                    ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) == PackageManager
                            .PERMISSION_GRANTED &&
                    ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == PackageManager
                            .PERMISSION_GRANTED) {
                startActivityForResult(new Intent(FaultEditBaseActivity.this, CameraActivity.class), 100);
            } else {
                //不具有获取权限，需要进行权限申请
                ActivityCompat.requestPermissions(FaultEditBaseActivity.this, new String[]{
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.RECORD_AUDIO,
                        Manifest.permission.CAMERA}, GET_PERMISSION_REQUEST);
            }
        } else {
            startActivityForResult(new Intent(FaultEditBaseActivity.this, CameraActivity.class), 100);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 101) {
            Log.i("carsafe", "picture");
            mediaType = "0";
            localMediaUrl = data.getStringExtra("path");
            ImageUtil.bindImageView(upload_1, localMediaUrl, R.drawable.ic_default_photo);
            video_icon.setVisibility(View.INVISIBLE);
            upload_2.setVisibility(View.VISIBLE);
        }
        if (resultCode == 102) {
            Log.i("carsafe", "video");
            mediaType = "1";
            localMediaUrl = data.getStringExtra("path");
            String firstFramePath = data.getStringExtra("firstFrame");
            ImageUtil.bindImageView(upload_1, firstFramePath, R.drawable.ic_default_photo);
            video_icon.setVisibility(View.VISIBLE);
            upload_2.setVisibility(View.VISIBLE);
        }
        if (resultCode == 103) {
            Toast.makeText(this, "请检查相机权限~", Toast.LENGTH_SHORT).show();
        }
    }

    @TargetApi(23)
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == GET_PERMISSION_REQUEST) {
            int size = 0;
            if (grantResults.length >= 1) {
                int writeResult = grantResults[0];
                //读写内存权限
                boolean writeGranted = writeResult == PackageManager.PERMISSION_GRANTED;//读写内存权限
                if (!writeGranted) {
                    size++;
                }
                //录音权限
                int recordPermissionResult = grantResults[1];
                boolean recordPermissionGranted = recordPermissionResult == PackageManager.PERMISSION_GRANTED;
                if (!recordPermissionGranted) {
                    size++;
                }
                //相机权限
                int cameraPermissionResult = grantResults[2];
                boolean cameraPermissionGranted = cameraPermissionResult == PackageManager.PERMISSION_GRANTED;
                if (!cameraPermissionGranted) {
                    size++;
                }
                if (size == 0) {
                    startActivityForResult(new Intent(FaultEditBaseActivity.this, CameraActivity.class), 100);
                } else {
                    Toast.makeText(this, "请到设置-权限管理中开启", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

    /*protected void onRequestPermissionsGranted(int requestCode) {
        if (requestCode == 100) {
            checkPermissions(new String[]{Manifest.permission.CAMERA}, 101);
        }else if(requestCode == 101){
            selectPicFromCamera();
        }
    }

    *//**
     * 通过照相得到照片
     *//*
    public void selectPicFromCamera() {
        if (!(Environment.getExternalStorageState()
                .equals(Environment.MEDIA_MOUNTED))) {
            Toast.makeText(getApplicationContext(), "SD卡不存在，不能拍照",
                    Toast.LENGTH_SHORT).show();
            return;
        }

        File dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/safe");
        if(!dir.exists()){
            dir.mkdir();
        }
        cameraFile = new File(dir, System.currentTimeMillis() + ".jpg");

        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if(Build.VERSION.SDK_INT >= 24) { //判读版本是否在7.0以上
            //参数1 上下文, 参数2 Provider主机地址 和配置文件中保持一致   参数3  共享的文件
            Uri apkUri = FileProvider.getUriForFile(this, "com.lishu.carsafe.fileprovider", cameraFile);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, apkUri);
        }else {
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(cameraFile));
        }
        startActivityForResult(intent, 99);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == RESULT_OK && requestCode == 99){
            if (cameraFile != null && cameraFile.exists()){
                try {
                    //1、得到新拍的照片
                    localImageUrl = cameraFile.getAbsolutePath();
                    LogUtil.d("sendFileLocalPath="+localImageUrl);
                    //2.1、压缩图片
                    //2.2、加入List
                    //3、更新显示
                    ImageUtil.bindImageView(upload_1, localImageUrl, R.drawable.ic_default_photo);
                    upload_2.setVisibility(View.VISIBLE);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }*/

    protected void sendPicture(final UploadFileListener uploadFileListener) {
        showAlways("正在处理，请稍候...");
        HttpLoader.uploadFile("fault", localMediaUrl, new HttpBase.IResponseListener() {
            @Override
            public void onResponse(BaseModel model) {
                if (model == null) {
                    hide();
                    ToastUtil.showShort(R.string.please_check_network);
                    return;
                }
                if (!model.success()) {
                    hide();
                    ToastUtil.showShort(getString(R.string.get_data_fail) + model.getMsg());
                    return;
                }
                UploadFileModel uploadFileModel = (UploadFileModel) model;
                if (uploadFileModel != null) {
                    uploadedMediaUrl = uploadFileModel.getData();
                }

                uploadFileListener.uploadFileSuccess(mediaType, uploadedMediaUrl);
            }
        });
    }

}
